<template>
  <view class="m-page-immersive">
    <view v-if="showFullscreenVideo" class="m-module-video">
      <view v-if="pageModule" class="m-full-video">
        <p-video
          :muted.sync="videoMuted"
          :query="query"
          :store-info="storeInfo"
          :pv="watchers"
          :share-count="shareCount"
          ref="ref-module-video"
          @change="handleVideoChange"
          @success="onCustomEvent"
          @buy="showBuy"
        />
      </view>
      <!--顶部-->
      <view v-if="openProduct !== 2" class="navigation-bar">
        <x-navigation-bar
          :storeId="pageInfo.storeId"
          color="#fff"
          icon-color="#fff"
          background="transparent"
        >
          <view class="header">
            <view v-if="storeInfo && pageType === 2" class="title-bar">
              <view class="logo">
                <x-image :src="storeInfo.storeLogo" />
              </view>
              <text>{{ storeInfo.storeName }}</text>
            </view>
          </view>
        </x-navigation-bar>
        <view v-if="isShowPv" class="view-pv">
          <x-icon name="icon-055" size="30" color="#fff" />
          <text>{{ watchers }}人观看</text>
        </view>
      </view>
    </view>
    <view v-if="!isDeleted" :class="moduleProductClass">
      <view v-if="openProduct && productInfo" class="m-module-body">
        <scroll-view
          :scroll-top="scrollViewTop"
          :scroll-y="isScrollViewScroll"
          enhanced
          scroll-anchoring
          class="m-scroll-view"
          @scroll="handlePageScrollView"
          @dragend="handleDragEnd"
          @scrolltoupper="handlePageScrollToupper"
          @scrolltolower="handleReachBottom"
        >
          <x-touch id="ref-page-all" :disabled="isShowFormOrder" @change="handleProductChange">
            <!--标题栏-->
            <x-navigation-bar
              v-if="openProduct === 2"
              :placeholder="false"
              :color="navigationColor"
              :background="navigationBg"
              :title="pageInfo.pageTitle"
              is-show-close
              @on-close="handleCloseModule"
              :subscribeNode="exitPopupList.length > 0 ? '' : 7"
              :storeId="pageInfo.storeId"
            />
            <!--轮播图-->
            <p-swiper v-if="indexPic" :index-pic="indexPic" :index-video="indexVideo" />
            <!-- 商品价格 -->
            <p-price v-if="pageInfo" :query="query" />
            <!-- 轮播图下面价格部分 -->
            <view class="goods-content">
              <!-- 品牌 -->
              <view class="brand">
                <view class="lf">
                  <view ref="page-title" class="_title" v-if="pageInfo">
                    <text v-if="pageModule.marketingLabel" class="tag tag-brand">{{ pageModule.marketingLabel.value }}</text>
                    {{ pageInfo.pageProductTitle }}
                  </view>
                  <x-button class="rt" size="none" styles="background: none;padding: 0" @click="openShareVisible">
                    <view class="_share">
                      <x-icon name="icon-023" size="44" color="#EB441F"></x-icon>
                      <text>分享</text>
                    </view>
                  </x-button>
                </view>
              </view>
              <view class="product-selling-point" style="display: flex">
                <view class="_introduce">{{ pageInfo.pageSellingPoint || '' }}</view>
              </view>
              <!-- 品牌 -->
              <view class="store" v-if="brandInfo">
                <view class="_logo">
                  <x-image :src="formatOss(brandInfo.brandLogo,100)" />
                </view>
                <view class="_name">{{ brandInfo.brandName }}</view>
                <view class="_vertical-line" />
                <view class="_introduce">{{ brandInfo.brandDesc }}</view>
              </view>
            </view>

            <!-- 服务 -->
            <p-server v-if="pageModule.servicePromise && safeguardList && safeguardList.length > 0" :serveList="safeguardList" suffix @showServiceDrawer="serviceVisible = true"/>

            <!-- 中部按钮 -->
            <p-buy-button v-if="pageModule.middleButton" :detail="pageModule.middleButton" placement="middle" @click="showBuy" />

            <!-- 跑马灯 -->
            <view v-if="carouselList" style="margin-top: 16rpx">
              <x-carousel :list="carouselList" :header="carouselHeader" button-text="马上抢" @change="showBuy" />
            </view>

            <!-- 用户评价 -->
            <template v-if="pageModule.productComment">
              <p-apprise :product-id="pageInfo.productId" :label="productInfo.commentLabelSelected" />
            </template>

            <!-- 店铺 -->
            <p-store
              v-if="pageInfo.storeId"
              :storeEntrance="pageModule.storeEntrance"
              :storeRecommend="pageModule.storeRecommend"
              :storeId="pageInfo.storeId"
              :storeInfo="storeInfo"
              :productId="pageInfo.productId"
            />

            <!--商品介绍/规格信息-->
            <p-details v-if="productInfo" :product-attr="productInfo.productAttrValues" :product-images="productImages" />

            <!-- 填写订单 -->
            <view id="form-order" ref="form-order" class="form-order">
              <view class="title">填写订单</view>
              <view class="pop_info">
                <p-order-info
                  ref="orderInfoDetail"
                  v-if="productInfo && isGetCouponList"
                  :query="query"
                  :detail="productInfo"
                  :page-id="query.pageId"
                  :product-id="pageInfo.productId"
                  :store-info="storeInfo"
                  :animate-end="beforeAnimateEnd"
                  :discount-price-sum.sync="discountPriceSum"
                />
              </view>
            </view>

            <!-- 悬浮客服按钮 -->
            <p-customer-service v-if="isShowCustomerService" :store-info="storeInfo" :session-from="sessionFrom" :share-customer-data="shareCustomerData" />

            <!-- 固底购买按钮 -->
            <view v-if="isShowBottomButton" :class="['footer', hideFooter ? 'is-hide' : '']">
              <p-fixed-discount v-if="scrolled" :price="discountPriceSum" :gift="productGiftInfo" />
              <p-buy-button :detail="pageModule.bottomButton" @click="showBuy" />
            </view>

          </x-touch>
        </scroll-view>
        <view v-if="openProduct === 1" class="m-close-module" @click="handleCloseModule">
          <x-icon name="icon-025" color="#fff" size="28" />
        </view>
      </view>
    </view>

    <!--悬浮表单-->
    <x-drawer :visible.sync="isShowFormOrder" isScroll>
      <view v-if="isShowFormOrder && productInfo && isGetCouponList" :scroll-y="true" class="m-pop-order-info">
        <view class="pop_header">
          <view>填写订单</view>
          <view class="pop_close" @click="isShowFormOrder = false">
            <x-icon name="icon-025" color="#333333" size="26"/>
          </view>
        </view>
        <view class="pop_header-placeholder"></view>
        <scroll-view class="pop_info" :scroll-y="true">
          <p-order-info
            ref="orderInfo"
            is-drawer
            :query="query"
            :detail="productInfo"
            :page-id="query.pageId"
            :product-id="pageInfo.productId"
            :store-info="storeInfo"
            :animate-end="beforeAnimateEnd"
            :discount-price-sum.sync="discountPriceSum"
          />
        </scroll-view>
      </view>
    </x-drawer>

    <!--分享海报-->
    <view class="p-poster" catchtouchmove="true" v-if="posterVisible">
      <view class="p-container" v-if="posterLoad">
        <view class="close-icon" @click="closePoster">
          <x-icon name="icon-003" size="54" color="#CCCCCC"/>
        </view>
        <view class="_img">
          <x-image :src="posterImage" mode="widthFix" />
        </view>
        <view class="save-poster" @click="saveImage">
          保存图片
        </view>
      </view>
    </view>
    <!--服务信息抽屉-->
    <p-drawer-service v-if="serviceVisible" :visible.sync="serviceVisible" :serveList="safeguardList" />
    <!--分享-->
    <p-drawer-share v-if="shareVisible" :visible.sync="shareVisible" :detail="shareData" from="immersive" @shareImage="shareImage" />
    <!--错误提示-->
    <p-deleted-box v-if="isDeleted" :productId="pageInfo.productId" class="p-deleted-box" />
    <x-countdown v-if="beforeAnimateEnd" :time="299000" auto @change="handleCountdownChange"/>
    <!--新挽留弹窗-->
    <x-pop-ups
      v-if="payCancelTwoVisible && exitPopupList.length > 0 && isShowExitPopup"
      :visible.sync="stayPopupVisible"
      @ready="scrollToFormOrder"
      @confirm="onDiscountPay"
    />
    <!--优惠券领取弹框-->
    <p-coupon-drawer
      v-if="isShowCoupon"
      :couponStyleImageUrl="couponStyleImageUrl"
      :allCouponSend="allCouponSend"
      :query="query"
      @onSendCoupon="onCustomEvent"
      @onCloseCoupon="onCloseCustomEvent"
    />
  </view>
</template>

<script>
import $sr from '@/utils/x-sr';
import { mapState } from 'vuex';
import XNavigationBar from '@/components/x-navigation-bar';
import XImage from '@/components/x-image';
import XIcon from '@/components/x-icon';
import XButton from '@/components/x-button';
import XCarousel from '@/components/x-carousel';
import XTouch from '@/components/x-touch';
import XDrawer from '@/components/x-drawer';
import XCountdown from '@/components/x-countdown';
import XPopUps from '@/components/x-pop-ups';
import PVideo from './components/p-video';
import PBuyButton from '../advertising/components/p-buy-button';
import PSwiper from '../advertising/components/p-swiper';
import PDetails from '../advertising/components/p-details';
import PCouponDrawer from '../advertising/components/p-coupon-drawer';
import POrderInfo from '../advertising/components/p-order-info';
import PPrice from '../advertising/components/p-price';
import PCustomerService from '../advertising/components/p-customer-service';
import PFixedDiscount from '../advertising/components/p-fixed-discount';
import PDeletedBox from '../goods-detail/components/p-deleted-box';
import PDrawerShare from '../goods-detail/components/p-drawer-share';
import PDrawerService from '../goods-detail/components/p-drawer-service';
import PServer from '../goods-detail/components/p-server';
import PApprise from '../goods-detail/components/p-apprise';
import PStore from '../goods-detail/components/p-store';

// 相交区域
let ObserverForm = null;
// 滑动结束防抖计时
let dragendTime = null;
// 页面滑动位置
let pageScrollTop = 0;
// 重试次数
let HTTP_RETRY_COUNT = 0;

export default {
  name: 'Immersive',
  components: {
    XCountdown,
    XNavigationBar,
    XCarousel,
    XTouch,
    XDrawer,
    XButton,
    XIcon,
    XImage,
    XPopUps,
    PSwiper,
    PFixedDiscount,
    PDetails,
    PBuyButton,
    PPrice,
    POrderInfo,
    PCouponDrawer,
    PCustomerService,
    PStore,
    PApprise,
    PServer,
    PDeletedBox,
    PDrawerShare,
    PDrawerService,
    PVideo
  },
  props: {},
  data() {
    return {
      query: {},
      isDeleted: false,
      // 服务弹框
      serviceVisible: false,
      // 是否可用优惠价
      isCouponPrice: false,
      // 是否显示过表单
      StartShowFrom: false,
      // 优化
      // 页面是否滚动过
      scrolled: false,
      // 品牌信息
      brandInfo: null,
      // 分享海报
      posterVisible: false,
      posterImage: '',
      posterLoad: false,
      // 观看人数
      watchers: 0,
      // 分享人数
      shareCount: 0,
      // 视频禁音状态
      videoMuted: false,
      scrollViewTop: 0,
      // 返回之后的优惠金额弹框
      exitPopupValue: 2,
      // 分享弹框
      shareVisible: false,
      // 隐藏底部按钮
      hideFooter: false,
      // 分享出去的海报信息
      shareData: {},
      //  店铺信息
      storeInfo: null,
      // 客服按钮卡片信息等
      shareCustomerData: null,
      // 客服按钮附加信息
      sessionFrom: null,
      // 悬浮表单
      isShowFormOrder: false,
      // 优惠券列表是否已经获取过
      isGetCouponList: false,
      // 标题栏透明度
      opacity: 0,
      // 当前页面挽留弹窗状态
      stayPopupVisible: false,
      // 挽留弹框动效即将结束前
      beforeAnimateEnd: false,
      // 当前挽留弹框是否显示过
      isShowExitPopup: true,
      // 错误情况下轮询获取信息定时器
      getPageDetailTimeout: null,
      getProductDetailTimeout: null,
      // 显示/隐藏交互优惠券弹框
      couponDrawerVisible: false,
      couponStyleImageUrl: '',
      // 优惠总金额
      discountPriceSum: 0,
      // 下单有礼数量
      productGiftInfo: 0
    };
  },
  computed: {
    ...mapState({
      // app onShow 场景值
      scene: state => state['pages'].scene,
      // 设备信息
      windowInfo: state => state['product'].windowInfo,
      // 0关闭，1半打开，2全打开
      openProduct: state => state['product'].openProduct,
      // 页面信息
      pageInfo: state => state['product'].pageDetail,
      // 页面模块
      pageModule: state => state['product'].pageModule || {},
      // 商品信息
      productInfo: state => state['product'].productDetail,
      // 服务承诺
      safeguardList: state => state['product'].safeguardList,
      // 当前商品可使用的优惠券
      couponList: state => state['product'].couponList || [],
      // 跑马灯数据
      carouselList: state => state['product'].carouselList,
      carouselTitle: state => state['product'].carouselTitle,
      // 当前是否领取过优惠券
      isSendCoupon: state => state['product'].isSendCoupon,

      // 投放页面初始数据
      pageQuery: state => state['pages'].pageQuery,
      // 返回出优惠金额弹框
      payCancelTwoVisible: state => state['pages'].payCancelTwoVisible,
      // 用户挽留弹框配置的优惠数组
      exitPopupList: state => state['pages'].exitPopupList,
      // 用户挽留弹框配置的优惠展示过的下标
      exitPopupIndex: state => state['pages'].exitPopupIndex,
      clearStoreStorage: state => state['pages'].clearStoreStorage,
      // 一键开启/关闭视频号场景挽留弹框
      popupStatus: state => state['pages'].popupStatus,
      // 当前商品关联的可领取优惠券，只支持批次领取，最多10个
      allCouponSend: state => state['product'].couponSend,
      // 商品主图
      indexPic: state => state['product'].resourceModule?.indexPic,
      // 主图视频
      indexVideo: state => state['product'].resourceModule?.indexVideo,
      // 商品图片资源
      productImages: state => state['product'].resourceModule?.detailPic?.picList || []
    }),
    // 页面类型
    pageType() {
      return Number(this.query.pageType);
    },
    navigationColor() {
      return `rgba(0,0,0,${this.opacity})`;
    },
    navigationBg() {
      return `rgba(255,255,255,${this.opacity})`;
    },
    // 是否展示沉浸视频模块
    showFullscreenVideo() {
      return !this.isDeleted;
    },
    // 商品模块class
    moduleProductClass() {
      const arr = ['m-module-page'];
      switch (this.openProduct) {
        case 0:
          break;
        case 1:
          arr.push('is-open');
          break;
        case 2:
          arr.push('is-full');
          break;
      }
      return arr.join(' ');
    },
    // 打开页面是否可以滑动
    isScrollViewScroll() {
      return this.openProduct === 2;
    },
    // 跑马灯顶部信息
    carouselHeader() {
      if (this.pageModule?.marquee) {
        return {
          title: this.carouselTitle,
          desc: this.pageModule.marquee.title
        };
      } else {
        return null;
      }
    },
    // 显示固底按钮
    isShowBottomButton() {
      return this.pageModule?.bottomButton && this.openProduct === 2;
    },
    // 是否显示pv数量
    isShowPv() {
      return this.watchers > 30 && this.pageType === 2 && this.pageModule?.pageView;
    },
    // 是否显示悬浮客服
    isShowCustomerService() {
      return !this.hideFooter && this.openProduct === 2 && this.pageModule?.customerService;
    },
    // 是否展示优惠券领取
    isShowCoupon() {
      return this.couponDrawerVisible &&
        this.allCouponSend &&
        !this.payCancelTwoVisible &&
        !['stay', 'groups', '1013', '1014'].includes(this.query.source);
    }
  },
  watch: {
    payCancelTwoVisible(value) {
      this.stayPopupVisible = value;
      if (value) {
        this.videoMuted = true;
      }
    }
  },
  onLoad(query) {
    let source = query.source || 'default';
    this.query = query;
    if (query.scene) { // 从小程序码进入
      const scene = this.$tools.param2Object(query.scene);
      this.query.pageId = scene.id;
      source = 'shareCode';
    } else {
      this.query.pageId = query.pageId || query.id;
    }
    // 重置计数
    HTTP_RETRY_COUNT = 1;
    // 重置store中的部分数据
    this.$store.dispatch('pages/setData', {
      payCancelTwoVisibleAgain: false,
      isCancelExitPopup: false,
      isConfirmPopup: false,
      isSendCoupon: false
    });
    if (!this.query.source) {
      this.$store.dispatch('product/reset');
      this.$store.dispatch('pages/fetchAppStore');
      this.$store.dispatch('product/setData', {
        openProduct: 0,
        isSendCoupon: false
      });
    }
    // 获取模块配置信息
    this.getPageDetail(query);
    this.$XTrack('source', source);
    // 刚进入投放页的时候，就上报一次日志
    this.$XTrack('onStart');
  },
  onShow() {
    // 重置滚动标识
    this.scrolled = false;
    this.setPreviousPath();
    // 如果是通过卡包进入的，给query增加马到自己的来源参数
    if ([1028, 1029].includes(this.scene)) {
      this.query = Object.assign(this.query, {
        source: '1008'
      });
    }
  },
  onHide() {
    // 页面加载之后，向数据团队上报特定消息
    this.$store.dispatch('pages/fetchReportViewAttr', this.query);

    // 离开页面后取消定时器
    if (this.getPageDetailTimeout) {
      clearTimeout(this.getPageDetailTimeout);
    }
    if (this.getProductDetailTimeout) {
      clearTimeout(this.getProductDetailTimeout);
    }
  },
  onUnload() {
    if (ObserverForm) ObserverForm.disconnect();
    // 页面加载之后，向数据团队上报特定消息
    this.$store.dispatch('pages/fetchReportViewAttr', this.query);

    // 离开页面后取消定时器
    if (this.getPageDetailTimeout) {
      clearTimeout(this.getPageDetailTimeout);
    }
    if (this.getProductDetailTimeout) {
      clearTimeout(this.getProductDetailTimeout);
    }
  },
  // 分享转发
  onShareAppMessage() {
    // 分享统计
    const { pageId, pageType } = this.query;
    this.$store.dispatch('product/setShareCount', {
      pageId
    }).then(() => {
      this.shareCount++;
    });
    const path = `/pages/immersive/index?pageId=${pageId}&pageType=${pageType || 2}&source=share`;
    this.$XTrack('onShareAppMessage');
    return {
      title: this.pageInfo.pageProductTitle,
      path
    };
  },
  methods: {
    numberFormat(val) {
      return this.$tools.numberFormat(val);
    },
    formatZero(val) {
      return this.$tools.formatZero(val);
    },
    // 格式化图片
    formatOss(url) {
      return this.$tools.formatOss(url);
    },
    showBuy(res) {
      if (this.openProduct !== 2) {
        // 半开的时候
        this.setOpenProduct(2);
      }
      const placement = res || '';
      let position = 'bottom';
      if (this.pageModule?.formStyle && this.pageModule.formStyle.value === 2 && res !== 'video') {
        // 定位到底部表单
        this.$nextTick(() => {
          this.scrollToFormOrder();
        });
      } else {
        // 展示悬浮表单
        this.isShowFormOrder = true;
        position = 'fixed';
      }
      // 中间购买按钮点击跳转到选择商品数量/规格 埋点上报
      this.$XTrack('middleBuyClick', {
        placement,
        position
      });
      if (res === 'video') {
        this.$XTrack('immersiveCardBuyClick');
      }
    },
    // 滚动到输入订单信息位置
    scrollToFormOrder() {
      // 选中节点的属性
      this.boundingClientRectSync('#form-order').then(res => {
        this.scrollViewTop = (res.top || 0) + pageScrollTop - (this.windowInfo.statusBarHeight + 48);
      });
    },
    // 监听页面滚动，处理顶部导航栏以及marquee
    handlePageScroll() {
      if (this.$refs['orderInfoDetail']) {
        this.$refs['orderInfoDetail'].scrollTab();
      }
    },
    // 获取观看人数
    getWatch() {
      this.$http({
        url: '/report/page/report/iu/pv',
        method: 'get',
        data: {
          pageId: this.query.pageId
        },
        report: false,
        error: false
      }).then((res) => {
        this.watchers = res.data;
      });
    },
    // 获取分享人数
    getShareCount() {
      this.$http({
        url: '/product/share/page/count',
        method: 'get',
        data: {
          pageId: this.query.pageId
        },
        report: false,
        error: false
      }).then((res) => {
        this.shareCount = res.data?.count;
      });
    },
    getCurrentPath() {
      const currPath = ['/pages/immersive/index'];
      const query = this.query;
      // 订阅消息场景获取
      const params = this.$tools.object2param(query);
      if (params) currPath.push(params);
      return currPath.join('?');
    },
    // 获取模块配置信息
    getPageDetail(query) {
      const params = {
        pageId: query.pageId,
        source: query.source,
        pageUrl: this.getCurrentPath()
      };
      // 必要参数校验
      if (!params.pageId) {
        this.isDeleted = true;
        return false;
      }
      this.$store.dispatch('product/getPageDetail', params).then((res) => {
        // 成功之后，重置计数
        HTTP_RETRY_COUNT = 1;
        const { pageDetail, pageModule } = res;
        const { pageStatus, popupStatus, pageId, storeId, productId, immersiveVideoUrl } = pageDetail || {};
        if (!res || pageStatus === 2) {
          // pageStatus	int	1-已上架（投放中）；2-已下架
          this.isDeleted = true;
        } else {
          // 当挽留弹框为不可用状态时，根据店铺视频号弹窗配置再进行重置
          if (!this.popupStatus) {
            this.$store.dispatch('pages/setData', {
              popupStatus: popupStatus === 1
            });

            // 视频号场景的时候、开关关闭的时候，直接返回到首页去
            if (!popupStatus) {
              this.$store.dispatch('pages/setData', {
                previousStatus: 99
              });
            }
          }
          // 获取商品详情数据
          this.getProductDetail();

          // 新互动优惠券弹框
          if (pageModule.couponStyle) {
            this.couponStyleImageUrl = pageModule.couponStyle.imageUrl;
          }

          // 只在source为空的时候初始化一次数据
          const pageQuery = {
            ...(this.pageQuery || {})
          };
          if (!query.source) {
            Object.assign(pageQuery, {
              pageId,
              storeId,
              productId,
              immersiveVideoUrl
            });
          }

          // 交易完成页查看订单按钮
          this.$store.dispatch('pages/setData', {
            pageQuery,
            isShowOrderButton: !!pageModule.orderEntrance
          });

          // 页面后退的优惠弹框类型
          if (pageModule.exitPopup) {
            this.exitPopupValue = pageModule.exitPopup.value;
          }

          // 聚合页信息
          if (pageModule.aggregatePage) {
            const { pageType } = pageModule.aggregatePage;
            // 单品页自己跳自己，聚合页跳动态生成页
            this.$store.dispatch('pages/setData', {
              groupsInfo: {
                pageType,
                pageId: this.query.pageId
              }
            });
          } else {
            this.$store.dispatch('pages/setData', {
              groupsInfo: null
            });
          }

          // 埋点
          try {
            const pageConfig = {
              groupsInfo: pageModule.aggregatePage ? {
                pageType: pageModule.aggregatePage.pageType
              } : null,
              exitPopup: pageModule?.exitPopup?.list || [],
              aggregatePage: pageModule?.aggregatePage || '',
              // 一键开启/关闭视频号场景挽留弹框
              popupStatus: pageDetail.popupStatus
            };
            this.$XTrack('logsMapIndex', {
              pageConfig
            });

            if (!['stay', '1022'].includes(this.query.source)) {
              let list = pageModule?.exitPopup?.list || [];
              if (!this.popupStatus) {
                // 视频号弹窗，状态控制，如果为关闭状态那么，不走挽留弹出流程
                list = [];
              }
              this.$store.dispatch('pages/setData', {
                exitPopupList: list,
                exitPopupIndex: 0
              });
            }
          } catch (e) {
            console.warn(e);
          }
        }
      }).catch(() => {
        HTTP_RETRY_COUNT++;
        this.getPageDetailTimeout = setTimeout(() => {
          this.getPageDetail(this.query);
        }, HTTP_RETRY_COUNT * 300);
      });
    },
    // 配置页面历史状态
    setPreviousPath() {
      const previous = {
        // 0，初始 1，投放页；2，挽留弹窗口，3，挽留页面, 12, 视频号
        previousStatus: 12,
        previousPath: '/pages/immersive/index',
        previousQuery: this.query
      };
      // 更新store访问数据
      // 通过url参数值进来的状态值
      if (this.query.previousStatus) {
        previous.previousStatus = +this.query.previousStatus;
        // 直接展示挽留弹窗
        if (previous.previousStatus === 2 && !this.isCancelExitPopup) {
          console.log('展示挽留弹框');
          previous.payCancelTwoVisible = true;
          // 展示挽留弹框的时候，直接设置成全打开状态
          this.setOpenProduct(2);
        }
      }
      if (this.groupsInfo) {
        // 用户挽留页信息
        const { publicityType, pageId } = this.groupsInfo;
        this.$XTrack('GroupsPageInfo', {
          type: publicityType,
          id: pageId
        });
      }
      if (this.clearStoreStorage) {
        this.$store.dispatch('pages/setData', previous);
      }
    },
    //  获取商品详情数据
    getProductDetail() {
      this.$store.dispatch('product/getProductDetail', {
        productId: this.pageInfo.productId,
        pageId: this.pageInfo.id,
        source: this.query.source
      }).then((res) => {
        // 成功之后，重置计数
        HTTP_RETRY_COUNT = 1;
        const { productDetail } = res;
        if (!res || productDetail.productStatus === 0) {
          // productStatus	int	0-已下架；1-已上架
          this.isDeleted = true;
        } else {
          // 设置分享海报信息
          this.shareData = {
            originalPrice: productDetail.originalPrice,
            productMainPic: productDetail.productMainPic,
            pageId: this.query.pageId,
            productTitle: this.pageInfo.pageProductTitle,
            sellingPrice: this.pageInfo.pagePrice
          };

          this.getCouponList(); // 获取可领取优惠券列表
          this.getCanSendCoupon(); // 获取可以发放的优惠券列表
          this.getStoreInfo(); // 获取商品信息后 获取店铺信息

          setTimeout(() => {
            // 获取观看人数
            this.getWatch();
            // 获取分享人数
            this.getShareCount();
            // 页面加载之后，向数据团队上报特定消息
            this.$store.dispatch('pages/fetchReportViewAttr', this.query).catch(() => {
              // 万一错误了，再试一次
              this.$store.dispatch('pages/fetchReportViewAttr', this.query);
            });
          }, 500);
          // 数据埋点
          this.$XTrack('push', {
            customerId: this.pageInfo.storeId,
            pageId: this.query.pageId,
            productId: this.pageInfo.productId
          });
          // 有数上报
          $sr.track('browse_sku_page', {
            'sku': {
              sku_id: this.query.pageId,
              sku_name: this.pageInfo.pageProductTitle
            },
            'spu': {
              spu_id: this.query.pageId,
              spu_name: this.pageInfo.pageProductTitle
            }
          });
        }
      }).catch(() => {
        HTTP_RETRY_COUNT++;
        this.getProductDetailTimeout = setTimeout(() => {
          this.getProductDetail();
        }, HTTP_RETRY_COUNT * 300);
      });
    },
    // 当前商品关联的可领取优惠券，只支持批次领取，最多10个
    getCanSendCoupon() {
      // 视频组件按钮需要这个数据
      this.$store.dispatch('product/getCouponSendList', {
        productId: this.pageInfo.productId,
        storeId: this.pageInfo.storeId,
        pageId: this.query.pageId,
        source: 1
      }).then((coupon) => {
        if (this.payCancelTwoVisible || !coupon) {
          this.couponDrawerVisible = false;
        }
      });
    },
    // 当前商品关联的可领取优惠券
    async getCouponList() {
      await this.$store.dispatch('product/getCouponList', {
        storeId: this.pageInfo.storeId,
        productId: this.pageInfo.productId,
        query: this.query || {}
      }).then(() => {
        this.isGetCouponList = true;
      }).catch(() => {
        this.isGetCouponList = true;
      });
    },
    // 关闭优惠券弹框
    onCloseCustomEvent() {
      // 订阅消息
      this.$store.dispatch('message/requestSubscribeMessage', {
        subscribeType: 1,
        subscribeNode: 100,
        subscribeContent: this.query.pageId,
        storeId: this.pageInfo.storeId,
        pageId: this.query.pageId
      });
      this.couponDrawerVisible = false; // 允许页面滑动并隐藏配置的优惠券弹框
    },
    // 领取优惠券并下单
    onCustomEvent(channel) {
      this.couponDrawerVisible = false;
      this.$store.dispatch('product/setData', {
        isSendCoupon: true,
        couponSend: null
      });
      // 投放页的优惠券列表数据刷新
      this.getCouponList();

      this.$XTrack('StartShowFrom', 'fixed');
      // 显示表单
      if (channel === 'video') {
        this.showBuy();
      }
    },
    //  获取店铺信息
    getStoreInfo() {
      const { source, pageId } = this.query;
      const payload = {
        storeId: this.pageInfo.storeId,
        pageId,
        source
      };
      this.$store.dispatch('product/getStoreInfo', payload).then((res) => {
        this.storeInfo = res.data;
        this.getGiftInfo();
      });
    },
    // 获取客服按钮信息
    getConfigData() {
      if (this.shareCustomerData) return false;
      this.$http({
        url: '/account/consulter/iu/app/detail',
        report: false,
        data: {
          storeId: this.pageInfo.storeId
        }
      }).then(res => {
        // console.log(res);
        this.shareCustomerData = res.data || {};
        this.sessionFrom = `【商品推广页】 页面标题：${this.pageInfo.pageName}；页面ID：${this.pageInfo.id}`;
      });
    },
    //  获取品牌
    getBrandInfo() {
      // 已有数据，不再请求
      if (this.brandInfo) return false;
      this.$http({
        login: true,
        url: '/product/brand/app/detail',
        method: 'get',
        report: false,
        data: {
          brandId: this.pageInfo.brandId
        }
      }).then(res => {
        this.brandInfo = res.data ? res.data : null;
      }).catch(err => {
        console.log(err);
      });
    },
    /**
     * 创建Observer
     * */
    createObserver() {
      ObserverForm = uni.createIntersectionObserver(this);
      ObserverForm
        .relativeToViewport()
        .observe('#form-order', (res) => {
          this.hideFooter = res.intersectionRatio > 0; // 相交区域占目标节点的布局区域的比例
          if (res.intersectionRatio > 0 && !this.StartShowFrom) {
            this.StartShowFrom = true;
            this.$XTrack('StartShowFrom', 'footer');
          }
        });
    },
    //  打开分享弹框
    openShareVisible() {
      this.shareVisible = true;
    },
    // 关闭分享海报
    closePoster() {
      this.posterVisible = false;
    },
    // 组件生成分享海报传值
    shareImage(res) {
      this.posterVisible = true;
      this.posterLoad = true;
      this.posterImage = res.posterImage;
      this.shareVisible = false;
    },
    //  点击保存海报
    saveImage() {
      uni.saveImageToPhotosAlbum({
        filePath: this.posterImage, //    图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
        success: () => {
          uni.showToast({
            title: '保存成功',
            duration: 2000
          });
          this.posterVisible = false;
        },
        fail: () => {
          uni.showToast({
            title: '保存失败',
            duration: 2000
          });
        }
      });
    },
    onStore() {
      uni.navigateTo({
        url: `/packages/store/index?storeId=${this.productInfo.storeId}`
      });
    },
    // 同步获取元素的属性
    boundingClientRectSync(selector) {
      return new Promise((resolve) => {
        uni.createSelectorQuery().select(selector).boundingClientRect((rect) => {
          resolve(rect || {});
        }).exec();
      });
    },
    async onDiscountPay(popupDetail) {
      this.$store.dispatch('pages/setData', { comboIndex: 0 });
      await this.showBuy();
      this.$store.dispatch('pages/setData', {
        payCancelTwoVisibleAgain: true,
        isConfirmPopup: true
      });
      this.$XTrack('StartShowFrom', 'fixed');
      // 展示优惠提示栏
      setTimeout(() => {
        this.beforeAnimateEnd = true;
      }, 300);
    },
    // 修改打开状态
    setOpenProduct(val) {
      this.$store.dispatch('product/setData', {
        openProduct: val
      });

      if ([1, 2].includes(val) && this.pageInfo?.brandId) {
        // 获取商品信息后 获取品牌信息
        this.getBrandInfo();
      }
      if (val === 2) {
        // 获取商品信息后 获取客服
        this.getConfigData();
      }

      this.$XTrack('immersiveStatusChange', val);
      // 当全部展示时获取页面窗口等信息
      if (val === 2) {
        try {
          this.$nextTick(() => {
            this.boundingClientRectSync('#ref-page-all').then(res => {
              const { pixelRatio, windowWidth, windowHeight } = this.windowInfo;
              const { width, height } = res;
              const pageWindowInfo = {
                pixelRatio,
                windowWidth,
                windowHeight,
                pageWidth: width,
                pageHeight: height
              };
              this.$XTrack('logsMapIndex', {
                pageWindowInfo
              });
            });
          });
        } catch (e) {
          console.warn(e);
        }
      }
    },
    // 视频组件状态切换
    handleVideoChange() {
      this.setOpenProduct(1);
      // 如果未领取过优惠券，那么半打开页面时再弹一次
      if (!this.couponDrawerVisible && !this.isSendCoupon) {
        this.couponDrawerVisible = true;
        this.$store.dispatch('product/setData', {
          isCancelCoupon: false
        });
      }
      this.$XTrack('immersiveCardClick');
    },
    // 商品区域手指滑动方向监听
    handleProductChange(val) {
      console.log(val);
      if (val === 'bottom') {
        // 全开，到半开
        if (this.openProduct === 2 && pageScrollTop <= 40) {
          this.setOpenProduct(1);
        } else if (this.openProduct === 1) {
          // 半开，到关闭
          this.setOpenProduct(0);
        }
      } else if (val === 'top') {
        this.setOpenProduct(2);
        this.createObserver();
      }
    },
    // 关闭
    handleCloseModule() {
      this.setOpenProduct(0);
      this.$XTrack('immersiveCardHideClick');
    },
    // 滚动到顶部/左边时触发
    handlePageScrollToupper() {
      pageScrollTop = 0;
    },
    // 商品内容滑动
    handlePageScrollView({ detail }) {
      const { scrollTop } = detail;
      this.handlePageScroll(scrollTop);

      const opacity = scrollTop / 44;
      if (opacity > 1) {
        this.opacity = 1;
      } else {
        this.opacity = opacity;
      }

      if (scrollTop > pageScrollTop) {
        // 页面最大滚动距离
        this.$XTrack('logsMapIndex', {
          maxPageScroll: scrollTop
        });
      }
      pageScrollTop = scrollTop;

      if (!this.scrolled) {
        this.$XTrack('pageScrolledEvent'); // 滚动事件埋点上报
        this.scrolled = true; // 滚动过
      }
    },
    // 滑动结束，有bug
    handleDragEnd() {
      if (dragendTime) {
        clearTimeout(dragendTime);
      }
      dragendTime = setTimeout(() => {
        this.scrollViewTop = pageScrollTop;
        dragendTime = null;
        // console.log('滑动结束-设置滚动条位置', pageScrollTop)
      }, 1800);
    },
    // 滚到页面底部
    handleReachBottom() {
      // 页面滑动到底部埋点
      this.$XTrack('onReachBottom');
    },
    // 倒计时更新
    handleCountdownChange(res) {
      this.$store.dispatch('pages/setData', {
        animateCountdownData: res
      });
      if (res.remain <= 0) {
        this.$store.dispatch('pages/setData', {
          animateCountdownData: false
        });
      }
    },
    // 获取支付有礼配置信息
    getGiftInfo() {
      this.$http({
        error: false,
        url: '/marketing/gift/app/count',
        data: {
          productId: this.pageInfo.productId,
          storeId: this.pageInfo.storeId
        }
      }).then((res) => {
        this.productGiftInfo = res.data;
      });
    }
  }
};
</script>

<style lang="scss">
  @import 'styles/put.scss';
</style>

<style lang="scss" scoped>
  .m-page-immersive{ background-color: #000;}
  .m-module-video{
    height: 100vh; overflow: hidden;
    .navigation-bar{ position: absolute; top: 0; left: 0;}
    .header{
      .title-bar{ display: flex; align-items: center; justify-content: flex-start; padding-left: 90px;}
      .logo{ width: 50px; height: 50px; border-radius: 50%; overflow: hidden; margin-right: 10px;}
    }
    .view-pv{
      display: flex; align-items: center; padding-left: 30px;
      text{ font-size: 28px; color: #fff; padding-left: 12px;}
    }
  }
  .m-close-module{ position: absolute; width: 54px; height: 54px; top: 24px; right: 24px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background-color: rgba(207, 207, 207, 0.5);}
  .m-module-page{
    position: absolute; width: 100%; height: calc(100vh - 250px); top: 100vh; background-color: #fff; opacity: 0; transition: .2s;
    &.is-open{ overflow: hidden; top: 250px; border-radius: 16px 16px 0 0; opacity: 1;}
    &.is-full{
      top: 0; height: 100vh; opacity: 1;
      .m-module-body{
        height: 100%;
        .m-scroll-view{ height: 100%;}
      }
    }
  }

  .m-module-body{
    display: flex; flex-direction: column; height: 100%;
    .m-scroll-view{ flex: 1; overflow: hidden; position: relative;}
  }
  .m-scroll-view{ background: #F7F8FA;}
</style>
